
import json
import datetime

from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework import status
from django.utils import timezone

from users.models import *
from .serializers import *
from users.serializers import UserSer
from users.utils import MyAlipay

# 标签管理
class LabelView(ViewSet):

    # 获取所有标签
    def label_desc(self, request):

        try:

            label = LabelModel.objects.filter(is_delete=False).all()
            label = LabelSer(label, many=True)
            label = json.loads(json.dumps(label.data))
            return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':label})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})

    # 添加标签
    def add_label(self, request):

        name = request.data.get('name')

        try:
            tag = LabelModel.objects.filter(name=name, is_delete=False).first()
            if tag:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '标签名称已经存在'})

            LabelModel.objects.create(name=name)

            return Response({'code': status.HTTP_200_OK, 'msg': '添加成功'})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})

    # 修改标签
    def upd_label(self, request, pk):

        name = request.data.get("name")

        try:
            label_list = LabelModel.objects.filter(id=pk, is_delete=False)
            if not label_list:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '没有此标签'})
            label_lst = LabelModel.objects.filter(name=name, is_delete=False)
            if label_lst:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '该标签已存在'})
            label_lst.update(name=name)
            return Response({'code':status.HTTP_200_OK, 'msg': '修改成功'})
        except Exception as e:
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR,'msg': f'服务器错误{e}'})

    # 删除标签
    def del_label(self, request, pk):
        try:
            label_list = LabelModel.objects.filter(id=pk, is_delete=False)
            if not label_list:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '没有此标签'})
            label_list.update(is_delete=True)
            return Response({"code": status.HTTP_200_OK, "msg": "删除成功"})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})

# 分类管理
class ClassifyView(ViewSet):

    # 获取所有分类
    def classify_desc(self, request):

        try:
            classify = ClassIfyModel.objects.filter(is_delete=False).all()
            classify = ClassifySer(classify, many=True)
            classify = json.loads(json.dumps(classify.data))
            for i in classify:
                class_list = ClassIfyModel.objects.filter(classify=i['id'], is_delete=False).all()
                class_list = ClassifySer(class_list, many=True)
                class_list = json.loads(json.dumps(class_list.data))
                i['classify_list'] = class_list
            return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':classify})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})

    # 添加分类
    def add_classify(self, request):

        name = request.data.get('name')
        sequence = request.data.get('sequence')
        classify_id = request.data.get('classify_id')

        try:
            classify = ClassIfyModel.objects.filter(name=name,is_delete=False).first()
            if classify:
                return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'分类已存在'})
            if classify_id:
                classify = ClassIfyModel.objects.filter(id=classify_id, is_delete=False).first()
                if not classify:
                    return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'分类不存在'})
            ClassIfyModel.objects.create(name=name,sequence=sequence,classify=classify_id)
            return Response({'code': status.HTTP_200_OK, 'msg': '添加成功'})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})

    # 修改分类
    def upd_classify(self, request, pk):

        name = request.data.get('name')
        sequence = request.data.get('sequence')

        try:
            classify_lst = ClassIfyModel.objects.filter(id=pk, is_delete=False)
            if not classify_lst:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '分类不存在'})
            classify = ClassIfyModel.objects.filter(name=name, is_delete=False).first()
            if classify:
                return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'分类已存在'})
            if name:
                classify_lst.update(name=name)
            if sequence:
                classify_lst.update(sequence=sequence)
            return Response({'code':status.HTTP_200_OK,'msg':'修改成功'})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})

    # 删除分类
    def del_classify(self, request, pk):

        try:
            classify = ClassIfyModel.objects.filter(id=pk, is_delete=False)
            if not classify:
                return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'分类不存在'})

            classify.update(is_delete=True)
            return Response({'code':status.HTTP_200_OK,'msg':'删除成功'})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})

# 学习内容
class ContentsView(ViewSet):

    # 获取所有学习内容
    def content_desc(self, request):

        user_id = request.query_params.get('user_id')

        try:
            contents = ContentsModel.objects.filter(user_id=user_id, is_delete=False).all()
            contents = ContentSer(contents, many=True)
            contents = json.loads(json.dumps(contents.data))
            return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':contents})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})

    # 添加学习内容
    def add_content(self, request):

        title = request.data.get('title')
        content = request.data.get('content')
        intro = request.data.get('intro')
        is_open = request.data.get('is_open')
        classify_name = request.data.get('classify_name')
        user_id = request.data.get('user_id')

        # 标签
        label1 = request.data.get('label1')
        label2 = request.data.get('label2')
        label3 = request.data.get('label3')

        try:
            titles = ContentsModel.objects.filter(title=title, is_delete=False).first()
            if titles:
                return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'内容已存在'})

            classify = ClassIfyModel.objects.filter(name=classify_name, is_delete=False).first()
            if not classify:
                return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'分类不存在'})

            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'用户不存在'})

            if is_open:
                ContentsModel.objects.create(title=title, content=content, intro=intro, is_open=True, classify_id=classify.id, user_id=user_id)
            else:
                ContentsModel.objects.create(title=title, content=content, intro=intro, classify_id=classify.id,user_id=user_id)

            contents = ContentsModel.objects.filter(title=title, content=content, intro=intro, classify_id=classify.id,user_id=user_id, is_delete=False).first()
            if label1:
                labels1 = LabelModel.objects.filter(id=label1, is_delete=False).first()
                Label_ContentModel.objects.create(content_id=contents.id, label_id=labels1.id)
            if label2:
                labels2 = LabelModel.objects.filter(id=label2, is_delete=False).first()
                Label_ContentModel.objects.create(content_id=contents.id, label_id=labels2.id)
            if label3:
                labels3 = LabelModel.objects.filter(id=label3, is_delete=False).first()
                Label_ContentModel.objects.create(content_id=contents.id, label_id=labels3.id)
            return Response({'code':status.HTTP_200_OK,'msg':'添加成功'})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})

    # 修改学习内容
    def upd_content(self, request, pk):

        title = request.data.get('title')
        content = request.data.get('content')
        intro = request.data.get('intro')
        is_open = request.data.get('is_open')

        try:

            titles = ContentsModel.objects.filter(title=title, is_delete=False)
            if titles:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '内容已存在'})

            titles = ContentsModel.objects.filter(id=pk, is_delete=False)
            if not titles:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '内容不存在'})

            if title:
                titles.update(title=title)
            if content:
                titles.update(content=content)
            if intro:
                titles.update(intro=intro)
            if is_open:
                titles.update(is_open=is_open)
            return Response({'code':status.HTTP_200_OK,'msg':'修改成功'})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})

    # 删除学习内容
    def del_content(self, reuqest, pk):

        try:
            titles = ContentsModel.objects.filter(id=pk, is_delete=False)
            if not titles:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '内容不存在'})

            titles.update(is_delete=True)
            return Response({'code':status.HTTP_200_OK,'msg':'删除成功'})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})

# 学习任务
class TaskView(ViewSet):

    # 发布学习任务
    def publish_content(self, request):

        user_id = request.data.get('user_id')
        content_title = request.data.get('content_title')

        try:
            user = UserModel.objects.filter(id=user_id, is_delete=False, teacher=None).first()

            contents = ContentsModel.objects.filter(title=content_title, is_delete=False, user_id=user_id).first()

            task = TaskModel.objects.filter(content_id=contents.id, clbum_id=user.clbum_id, is_delete=False).first()
            if task:
                return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'该任务已发布'})
            TaskModel.objects.create(content_id=contents.id, clbum_id=user.clbum_id)
            task = TaskModel.objects.filter(content_id=contents.id, clbum_id=user.clbum_id, is_delete=False).first()
            student_list = UserModel.objects.filter(clbum_id=user.clbum_id, teacher=user_id, is_delete=False).all()
            student_list = UserSer(student_list, many=True)
            student_list = json.loads(json.dumps(student_list.data))
            for i in student_list:
                RecordModel.objects.create(task_id=task.id, user_id=i['id'], is_status=1)
            return Response({'code':status.HTTP_200_OK,'msg':'发布成功'})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})

    # 获取学习任务
    def content_desc(self, request):
        user_id = request.query_params.get('user_id')

        try:
            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            task = TaskModel.objects.filter(clbum_id=user.clbum_id, is_delete=False).all()
            task = TaskSer(task,many=TaskSer)
            task = json.loads(json.dumps(task.data))
            return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':task})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误】{e}'})

    # 获取任务详情
    def desc_content(self, request, pk):

        user_id = request.query_params.get('user_id')

        try:
            task = TaskModel.objects.filter(id=pk, is_delete=False).first()
            if not task:
                return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'该任务不存在'})

            task = TaskSer(task)
            task = json.loads(json.dumps(task.data))
            content = ContentsModel.objects.filter(id=task['content'], is_delete=False).first()
            content = ContentSer(content)

            sta_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            record = RecordModel.objects.filter(user_id=user_id, is_delete=False, task_id=task['id'])
            record.update(start_time=sta_time)
            return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':content.data})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})


# 学习记录
class RecordView(ViewSet):

    # 获取老师下学生的学习记录
    def record_desc(self, request):
        user_id = request.query_params.get('user_id')

        try:
            user = UserModel.objects.filter(teacher=user_id, is_delete=False).all()
            user = UserSer(user, many=True)
            user = json.loads(json.dumps(user.data))
            for i in user:
                record = RecordModel.objects.filter(user_id=i['id'], is_delete=False).all()
                record = RecordSer(record,many=True)
                record = json.loads(json.dumps(record.data))

            return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':record})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})

    # 修改学习状态
    def upd_record(self, request):

        title = request.data.get('title')
        user_id = request.data.get('user_id')

        try:

            contents = ContentsModel.objects.filter(title=title,is_delete=False).first()
            tasks = TaskModel.objects.filter(content_id=contents.id, is_delete=False).first()
            record = RecordModel.objects.filter(task_id=tasks.id, user_id=user_id, is_delete=False).first()
            print(record)
            if not record:
                return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'学习记录不存在'})

            record = RecordSer(record)
            record = json.loads(json.dumps(record.data))
            print(record)

            start_time = record['start_time'].replace('T',' ')
            finish_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            tokinaga = datetime.datetime.strptime(finish_time, '%Y-%m-%d %H:%M:%S') - datetime.datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S')
            print(tokinaga,type(tokinaga))

            record = RecordModel.objects.filter(id=record['id'], is_delete=False)
            time1 = datetime.timedelta(seconds=86400)  # 24小时
            time2 = datetime.timedelta(seconds=3600)  # 6小时
            time3 = datetime.timedelta(seconds=21600)  # 1小时
            time4 = datetime.timedelta(seconds=1200)  # 20分钟
            if tokinaga >= time1 or tokinaga <= time4:
                print('作弊完成')
                record.update(tokinaga=tokinaga,is_status=2)
            if tokinaga <= time2 and tokinaga > time4:
                print('已完成')
                record.update(tokinaga=tokinaga,is_status=3)
            if tokinaga > time2 and tokinaga < time1:
                print('费力完成')
                record.update(tokinaga=tokinaga,is_status=4)

            record.update(finish_time=finish_time)

            return Response({'code':status.HTTP_200_OK,'msg':'修改成功'})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})

# 弹幕
class BarrageView(ViewSet):

    # 发送弹幕
    def add_barrage(self, request):

        user_id = request.data.get('user_id')
        content_id = request.data.get("content_id")
        name = request.data.get("name")
        try:
            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '该用户不存在'})

            contents = ContentsModel.objects.filter(id=content_id, is_delete=False).first()
            if not contents:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '该内容不存在'})
            BarrageModel.objects.create(name=name, user_id=user_id, content_id=content_id, like=0)

            return Response({'code': status.HTTP_200_OK, 'msg': '发送成功'})
        except Exception as e:
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': f'服务器错误{e}'})

    # 获取弹幕
    def barrage_desc(self, request):

        content_id = request.data.get('content_id')

        try:
            contents = ContentsModel.objects.filter(id=content_id, is_delete=False).first()
            contents = ContentSer(contents)
            contents = json.loads(json.dumps(contents.data))

            barrage = BarrageModel.objects.filter(content_id=contents["id"], is_delete=False).all()
            barrage = BarrageSer(barrage, many=True)
            barrage = json.loads(json.dumps(barrage.data))
            contents['barrage_list'] = barrage
            return Response({'code': status.HTTP_200_OK, 'msg': '获取成功', 'data': contents})
        except Exception as e:
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': f'服务器错误{e}'})

# 学习资源
class ResourceView(ViewSet):

    # 全部获取资源
    def list_resource(self, request):

        try:
            resource = ResourceModel.objects.all()
            resource = ResourceSer(resource, many=True)
            resource = json.loads(json.dumps(resource.data))
            return Response({'code': status.HTTP_200_OK, 'msg': '获取成功', 'data': resource})
        except Exception as e:
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': f'服务器错误{e}'})

    # 添加学习资源
    def add_resource(self, request):

        name = request.data.get('name')
        depict = request.data.get('depict')
        price = request.data.get('price')
        user_id = request.data.get('user_id')
        contents_title = request.data.get('contents_title')

        try:

            resource = ResourceModel.objects.filter(name=name, user_id=user_id, is_delete=False)
            if resource:
                return Response({'code':status.HTTP_400_BAD_REQUEST, 'msg':'该资源已经存在'})

            contents = ContentsModel.objects.filter(title=contents_title, user_id=user_id, is_delete=False).first()

            if contents_title:
                ResourceModel.objects.create(name=name, depict=depict, price=price, user_id=user_id, content_id=contents.id)
            else:
                ResourceModel.objects.create(name=name, depict=depict, price=price, user_id=user_id)
            return Response({'code': status.HTTP_200_OK, 'msg': '添加成功'})
        except Exception as e:
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': f'服务器错误{e}'})

    # 获取我的资源
    def my_resource(self, request):

        user_id = request.query_params.get('user_id')

        try:

            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '该用户不存在'})

            resource = ResourceModel.objects.filter(user_id=user_id, is_delete=False)
            resource = ResourceSer(resource, many=True)
            resource = json.loads(json.dumps(resource.data))
            return Response({'code': status.HTTP_200_OK, 'msg': '获取成功', 'data': resource})
        except Exception as e:
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': f'服务器错误{e}'})

    # 修改学习资源
    def upd_resource(self, request, pk):

        user_id = request.data.get('user_id')
        name = request.data.get("name")
        depict = request.data.get("depict")
        price = request.data.get("price")

        try:

            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '该用户不存在'})

            resources = ResourceModel.objects.filter(name=name, depict=depict, price=price, user_id=user_id, is_delete=False).first()
            if resources:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '该资源已存在'})

            resource = ResourceModel.objects.filter(user_id=user_id, id=pk, is_delete=False)
            if not resource:
                return Response({'code': status.HTTP_400_BAD_REQUEST,'msg':'该用户没有此资源'})

            if name:
                resource.update(name=name)
            if depict:
                resource.update(depict=depict)
            if price:
                resource.update(price=price)

            return Response({'code': status.HTTP_200_OK, 'msg': '修改成功'})
        except Exception as e:
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': f'服务器错误{e}'})

    # 删除我的学习资源
    def del_resource(self, request, pk):

        user_id = request.data.get('user_id')

        try:

            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '该用户不存在'})

            resource = ResourceModel.objects.filter(id=pk, user_id=user_id, is_delete=False)
            if not resource:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '该资源不存在'})

            resource.update(is_delete=True)

            return Response({'code': status.HTTP_200_OK, 'msg': '删除成功'})
        except Exception as e:
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': f'服务器错误{e}'})

# 订单
class OrderView(ViewSet):

    myalipay = MyAlipay()

    # 提交订单
    def add_order(self, request):
        try:
            user_id = request.data.get('user_id')
            pay_method = request.data.get('pay_method')
            total_amount = request.data.get('total_amount')
            resource_id = request.data.get('resource_id')
            print(user_id, pay_method, total_amount)

            order_id = datetime.datetime.now().timestamp()
            # 订单编号
            OrderModel.objects.create(user_id=user_id, pay_method=pay_method,resource_id=resource_id,
                                              total_amount=total_amount, order_id=order_id)

            return_url = 'http://127.0.0.1:8000/index/order'
            url = self.myalipay.get_pay_url(order_id, total_amount, return_url)
            return Response({'code': status.HTTP_200_OK, 'msg': '创建成功', 'url': url})
        except Exception as e:
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': f'服务器错误{e}'})

    # 判断订单是否支付成功
    def check_order(self, request):

        order_id = request.data.get('order_id')

        try:
            order = OrderModel.objects.filter(order_id=order_id, is_delete=False)

            if not order:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '该订单不存在'})

            if not self.myalipay.check(order_id):
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '没有支付'})

            order.update(pay_state=1)
            return Response({'code': status.HTTP_200_OK, 'msg': '支付成功'})

        except Exception as e:
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': f'支付失败,原因{e}'})

    # 获取用户的所有订单
    def list_order(self, request):

        user_id = request.data.get('user_id')

        try:
            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'该用户不存在'})

            order = OrderModel.objects.filter(user_id=user_id, is_delete=False).all().order_by('-create_date')
            order = OrderSer(order, many=True)
            order = json.loads(json.dumps(order.data))

            for i in order:
                resource = ResourceModel.objects.filter(id=i['id'], is_delete=False).first()
                resource = ResourceSer(resource)
                resource = json.loads(json.dumps(resource.data))
                i['resource_list'] = resource

            return Response({'code': status.HTTP_200_OK, 'msg': '获取成功', 'data': order})
        except Exception as e:
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': f'服务器错误{e}'})

    # 获取订单的详情
    def order_get_details(self, request, pk):

        user_id = request.data.get('user_id')

        try:

            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '该用户不存在'})

            order = OrderModel.objects.filter(user_id=user_id, id=pk, is_delete=False)
            if not order:
                return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'该订单不存在'})

            order = OrderModel.objects.filter(id=pk, user_id=user_id, is_delete=False).first()
            order = OrderSer(order)
            order = json.loads(json.dumps(order.data))
            resource = ResourceModel.objects.filter(id=order['resource'], is_delete=False).all()
            resource = ResourceSer(resource, many=True)
            resource = json.loads(json.dumps(resource.data))
            order['resource_list'] = resource
            return Response({'code': status.HTTP_200_OK, 'msg': '获取订单详情成功', 'data': order})
        except Exception as e:
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': f'服务器错误{e}'})

    # 取消支付订单
    def not_order_del(self, request, pk):

        user_id = request.data.get('user_id')

        try:

            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '该用户不存在'})

            order = OrderModel.objects.filter(id=pk, user_id=user_id, pay_state=0, is_delete=False)
            if not order:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '该订单不存在'})

            order.update(is_delete=True)

            return Response({'code': status.HTTP_200_OK, 'msg': '取消支付成功'})
        except Exception as e:
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': f'服务器错误{e}'})

    # 删除订单
    def order_del(self, request, pk):

        user_id = request.data.get('user_id')

        try:

            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '该用户不存在'})

            order = OrderModel.objects.filter(id=pk, user_id=user_id, is_delete=False)
            if not order:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '该订单不存在'})

            order.update(is_delete=True)

            return Response({'code': status.HTTP_200_OK, 'msg': '删除成功'})
        except Exception as e:
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': f'服务器错误{e}'})

# 收藏
class CollectView(ViewSet):

    # 添加收藏
    def add_collect(self, request, pk):

        user_id = request.data.get('user_id')
        try:

            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '该用户不存在'})

            resource = ResourceModel.objects.filter(id=pk, is_delete=False).first()
            if not resource:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '该资源不存在'})

            collect = CollectModel.objects.filter(user_id=user_id, resource_id=resource.id, is_delete=False).first()
            if collect:
                return Response({'code': status.HTTP_400_BAD_REQUEST,'msg': '此资源已经收藏'})

            collect = CollectModel.objects.filter(user_id=user_id, resource_id=resource.id, is_delete=True)
            if collect:
                collect.update(is_delete=False)
            else:
                CollectModel.objects.create(user_id=user_id, resource_id=resource.id)

            return Response({'code': status.HTTP_200_OK, 'meg': '收藏成功'})
        except Exception as e:
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'meg': f'服务器错误{e}'})

    # 取消收藏
    def del_collect(self, request, pk):

        user_id = request.query_params.get('user_id')

        try:

            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '该用户不存在'})

            resource = ResourceModel.objects.filter(id=pk, is_delete=False).first()
            if not resource:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '该资源不存在'})

            collect = CollectModel.objects.filter(user_id=user_id, resource_id=resource.id, is_delete=False)
            if not collect:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '该用户没有收藏这个资源'})
            collect.update(is_delete=True)
            return Response({'code': status.HTTP_200_OK, 'meg': '取消收藏成功'})
        except Exception as e:
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'meg': f'服务器错误{e}'})

    # 获取我收藏的资源
    def collect_list(self, request):

        user_id = request.query_params.get('user_id')

        try:
            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'该用户不存在'})

            collect = CollectModel.objects.filter(user_id=user_id, is_delete=False).all()
            collect = CollectSer(collect, many=True)
            collect = json.loads(json.dumps(collect.data))

            lst = []
            for i in collect:
                resource = ResourceModel.objects.filter(id=i['resource'], is_delete=False).first()
                resource = ResourceSer(resource)
                resource = json.loads(json.dumps(resource.data))
                lst.append(resource)

            return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':lst})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})



